﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace IMMeDotNet {

	partial class Host {

		/// <summary>
		/// Write a raw array of bytes directly to the device.
		/// </summary>
		/// <param name="data">The data to write.</param>
		private void Write(byte[] data) {
			for (byte i = 0; i < data.Length; ++i) {
				var report = new byte[this.wirelessAdaptorCapabilities.OutputReportByteLength];
				report[this.wirelessAdaptorCapabilities.NumberOutputDataIndices + 0] = i;
				report[this.wirelessAdaptorCapabilities.NumberOutputDataIndices + 1] = data[i];
				this.wirelessAdaptorStream.Write(report, 0, report.Length);
				Thread.Sleep(5); // HACK
			}
			Thread.Sleep(50); // HACK
		}

		/// <summary>
		/// Write a <see cref="Packet"/> to the device.
		/// </summary>
		/// <param name="packet">The <see cref="Packet"/> to write.</param>
		private void Write(Packet packet) {
			var packetData = packet.ToBytes();
			var prefixedPacketData = new byte[packetData.Length + 3];
			prefixedPacketData[0] = 0xFA;
			prefixedPacketData[1] = 0xFB;
			prefixedPacketData[2] = (byte)packetData.Length;
			Array.Copy(packetData, 0, prefixedPacketData, 3, packetData.Length);
			this.Write(prefixedPacketData);
			#if POLLED_USB_INPUT
			this.wirelessAdaptorStream.Read(new byte[3], 0, 3);
			#endif
		}

		/// <summary>
		/// Write a <see cref="Message"/> to the device.
		/// </summary>
		/// <param name="message">The <see cref="Message"/> to write.</param>
		private void Write(OutgoingUsbMessage message) {
			foreach (var packet in message.ToPackets()) {
				this.Write(packet);
			}
		}

	}
}
